package br.com.felix.dbm.ui.components;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTextField;

import br.com.felix.dbm.controller.ColumnController;
import br.com.felix.dbm.database.DataSize;
import br.com.felix.dbm.database.DataType;

/**
 * User interface for column's data size.
 * */
public class DataSizeJTextField extends JTextField {

	private static final long serialVersionUID = 7180537787509737143L;

	/**
	 * Key Adapter to allow only numbers and commas. Automatically updates the
	 * associated column model.
	 * */
	class DataSizeKeyAdapter extends KeyAdapter {

		@Override
		public void keyReleased(KeyEvent e) {
			JTextField jTextField = (JTextField) e.getSource();
			e.consume();
			String valid;
			if (numArgs == 0) {
				valid = "0123456789";
			}
			else {
				valid = "0123456789,";
			}
			String text = jTextField.getText();
			if (text.length() > 0) {
				char last = text.charAt(text.length() - 1);
				if (valid.indexOf(last) < 0) {
					text = text.substring(0, text.length() - 1);
					jTextField.setText(text);
				}
			}
			DataSize newDataSize = new DataSize(jTextField.getText());
			if (!newDataSize.equals(columnController.getModel().getSize())) {
				columnController.setSize(newDataSize);
				columnController.updateView();
			}
		}
	}

	private ColumnController columnController;



	public DataSizeJTextField(ColumnController columnController) {
		this.columnController = columnController;
		addKeyListener(new DataSizeKeyAdapter());
		setColumns(2);
	}

	private int numArgs = 0;



	/**
	 * Disables size editing if data type does not required size specification.
	 * */
	public void setDataType(DataType dt) {
		numArgs = dt.getSizeArguments();
		switch (numArgs) {
			case 0:
				setText("");
				setEditable(false);
				break;
		}
	}

}
